import React, { useState, useEffect, useRef, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { connect } from "react-redux";
// useRef  DOM 相关
// useCallback 性能优化
import singerImg from "./singer.png";
import musicImg from "./music.png";

import {
  changeEnterLoading,
  getHotKeywords,
  getSuggestList,
} from "./store/actionCreators";
import { CSSTransition } from "react-transition-group";
import Scroll from "@/components/common/Scroll";
import { Container, ShortcutWrapper, HotKey } from "./style";
import SearchBox from "@/components/common/search-box";
import Loading from "@/components/common/loading";
import { EnterLoading, List, ListItem } from "./../Singers/style";
import Lazyload, { forceCheck } from "react-lazyload";
import { getName } from '@/api/utils'
import { SongItem } from '../Album/style'

const Search = (props) => {
  const navigate = useNavigate();
  const { 
    hotList, 
    songsCount, 
    enterLoading, 
    suggestList, 
    songsList
  } = props;
  console.log(songsList,"++++++")
  const {
    changeEnterLoadingDispatch,
    getHotKeywordDispatch,
    getSuggestListDispatch,
  } = props;
  // 搜索内容  redux 解决共享状态
  // 1. 搜索列表 api action redux
  const [query, setQuery] = useState("");
  const [show, setShow] = useState(false);

  const searchBack = () => {
    setShow(false);
  };
  useEffect(() => {
    setShow(true);
    if (!hotList.length) {
      getHotKeywordDispatch();
    }
  }, []);

  const handleQuery = (q) => {
    // console.log(q)
    setQuery(q);
  };
  useEffect(() => {
    // console.log(query,'888888')
    if (query.trim()) {
      // 去除空格 有必要去请求
      changeEnterLoadingDispatch(true);
      getSuggestListDispatch(query);
    }
  }, [query]);

  const renderHotKey = () => {
    let list = hotList ? hotList : [];
    return (
      <ul>
        {list.map((item) => {
          return (
            <li 
              className="item" 
              key={item.first}
              onClick={() => setQuery(item.first)}
              >
              <span>{item.first}</span>
            </li>
          );
        })}
      </ul>
    );
  };
  const gotoSingers = (id) => {
    navigate(`/singers/${id}`)
  }
  const renderSingers = () => {
    let singers = suggestList.artists;
    // console.log(singers)
    if (!singers || !singers.length) return;
    // console.log(singers);
    return (
      <List>
        <h1 className="title">相关歌手</h1>
        {singers.map((item, index) => {
          return (
            <ListItem 
              key={item.accountId + "" + index}
              onClick={() => gotoSingers(item.id)}
              >
              <div className="img_wrapper">
                <Lazyload
                  placeholder={
                    <img width="100%" height="100%" src={singerImg} />
                  }
                >
                  <img
                    src={item.picUrl}
                    alt="music"
                    width="100%"
                    height="100%"
                  />
                </Lazyload>
              </div>
              <span className="name">歌手：{item.name}</span>
            </ListItem>
          );
        })}
      </List>
    );
  };
  const gotoAlbum = (id) => {
    navigate(`/ablum${id}`)
  }
  const renderAlbum = () => {
    let albums = suggestList.playlists;
    if (!albums || !albums.length) return; // 最开始没有
    // console.log(albums);
    return (
      <List>
        <h1 className="title">相关歌单</h1>
        {albums.map((item, index) => {
          return (
            <ListItem 
              key={item.accountId + "" + index}
              onClick={() => gotoAlbum()}
              >
              <div className="img_wrapper">
                <Lazyload
                  placeholder={
                    <img
                      width="100%"
                      height="100%"
                      src={musicImg}
                      alt="music"
                    />
                  }
                >
                  <img
                    src={item.coverImgUrl}
                    alt="music"
                    width="100%"
                    height="100%"
                  />
                </Lazyload>
              </div>
              <span className="name">歌单：{item.name}</span>
            </ListItem>
          );
        })}
      </List>
    );
  };
  const renderSongs = () => {
    
    return (
      <SongItem style={{paddingLeft: "1rem"}}>
          {
              songsList.map(item => {
                return (
                    <li key={item.id}>
                        <div className="info">
                            <span>{item.name}</span>
                            <span>
                                { getName(item.artists) } - { item.album.name }
                            </span>
                        </div>
                    </li>
                )
              })
          }
      </SongItem>
    );
  };
  return (
    // 当 dom ready 即组件挂载上去后，应用一个css transition效果
    <CSSTransition
      in={show}
      timeout={300}
      appear={true}
      classNames="fly"
      unmountOnExit
      onExit={() => {
        navigate(-1);
      }}
    >
      {/* sc-evZas bAobGr fly-enter fly-enter-active */}
      <Container play={songsCount}>
        <div className="search_box_wrapper">
          <SearchBox
            back={searchBack}
            newQuery={query}
            handleQuery={handleQuery}
          ></SearchBox>
        </div>
        <ShortcutWrapper show={!query}>
          <Scroll>
            <div>
              <HotKey>
                <h2 className="title">热门搜索</h2>
                {renderHotKey()}
              </HotKey>
            </div>
          </Scroll>
        </ShortcutWrapper>
        <ShortcutWrapper show={query}>
          <Scroll onScroll={forceCheck}>
            <div>
              {renderSingers()}
              {renderAlbum()}
              {renderSongs()}
            </div>
          </Scroll>
        </ShortcutWrapper>
        {enterLoading && (
          <EnterLoading>
            <Loading />
          </EnterLoading>
        )}
      </Container>
    </CSSTransition>
  );
};
const mapStateToprops = (state) => {
  return {
    // api 数据请求 热搜
    hotList: state.search.hotList,
    enterLoading: state.search.enterLoading,
    // 搜索建议 卖广告
    suggestList: state.search.suggestList,
    // redux 就为跨模板共享数据而来
    songsCount: state.player.playList.length,
    songsList: state.search.songsList,
  };
};
const mapDispatchProps = (dispatch) => {
  return {
    getHotKeywordDispatch() {
      dispatch(getHotKeywords());
    },
    changeEnterLoadingDispatch(data) {
      dispatch(changeEnterLoading(data));
    },
    getSuggestListDispatch(data) {
      dispatch(getSuggestList(data));
    },
    // getSongListDispatch(){}
  };
};
export default connect(mapStateToprops, mapDispatchProps)(React.memo(Search));
